package com.ynet.middleground.riskmanage.model;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hundsun.jrescloud.common.gm.SM3Factory;
import com.ynet.core.exception.BusinessException;
import com.ynet.host.HostConstants;
import com.ynet.middleground.riskmanage.bean.cangdan.QueryCangDanFreezeReq;
import com.ynet.middleground.riskmanage.bean.cangdan.QueryCangDanTransferReq;
import com.ynet.middleground.riskmanage.dto.cangdan.QueryCangDanFreezeDTO;
import com.ynet.middleground.riskmanage.dto.cangdan.QueryCangDanTransferDTO;
import com.ynet.middleground.riskmanage.external.MainBusinessConfig;
import com.ynet.middleground.riskmanage.external.cangdan.CangDanUriEnum;
import com.ynet.middleground.riskmanage.external.newrizhaogang.NewRzgApiHelper;
import com.ynet.middleground.riskmanage.external.qcc.ApiHelper;
import com.ynet.middleground.riskmanage.utils.ApiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName CangDanModel
 * @Description 电子仓单
 * @Author songyf
 * @Date 2022/11/28 17:32
 * @Version 1.0
 */
@Component
public class CangDanModel {
    @Autowired
    ApiUtil apiUtil;

    @Autowired
    ApiHelper apiHelper;

    @Autowired
    private NewRzgApiHelper newRzgApiHelper;

    @Autowired
    MainBusinessConfig mainBusinessConfig;

    public static final String LOG_NAME = "电子仓单";

    private static final String SUCCESS_FLAG = "0";

    //查询电子仓单冻结/解冻指令
    public List<QueryCangDanFreezeDTO> queryCangDanFreeze(QueryCangDanFreezeReq requestObj) {
        List<QueryCangDanFreezeDTO> returnsResult = new ArrayList<>();
        JSONObject json = new JSONObject();
        json.put("command_ids",requestObj.getCommand_ids());
        json.put("cargokey",requestObj.getCargokey());
        json.put("channel_no",requestObj.getChannel_no());
        json.put("operate_type",requestObj.getOperate_type());
        // 1.请求参数json串reqContent
        String reqContent = json.toJSONString();
        // 2.随机生成的16位数字，用于签名（双方提前约定一串固定字符串，不在接口中传输）APP_ID: rzPort22
        String appSecret = mainBusinessConfig.getDzcdAppSecret();
        // 3.当前时间戳14位字符串timestamp，格式为"yyyyMMddHHmmss"
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 4.对reqContent+appSecret+timestamp拼接后的字符串通过SM3算法进行签名，得到64位摘要字符串sign
        String plain = reqContent + appSecret + timestamp;
        String charset = "UTF-8";
        String sign = SM3Factory.getInstance().hashAndReturnHex(plain, charset);

        Map<String, String> header = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("function_id", CangDanUriEnum.CARGO_CONTROL_QUERY.getUrl());
        params.put("app_id", mainBusinessConfig.getDzcdAppId());
        params.put("timestamp", timestamp);
        params.put("sign", sign);
        params.put("req_content", json);
        JSONObject apiResult = newRzgApiHelper.sendApiLog(CangDanUriEnum.CARGO_CONTROL_QUERY.getCode(),
                mainBusinessConfig.getDzcdUrl(), header, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, requestObj);
        String code = apiResult.getString("error_code");
        if (!SUCCESS_FLAG.equals(code)) {
            String errorcode = code;
            String errormsg = apiResult.getString("error_msg");
            throw new BusinessException(errormsg, errorcode);
        }
        JSONObject rspContent= apiResult.getJSONObject("rsp_content");
        if (!SUCCESS_FLAG.equals(rspContent.getString("error_no"))) {
            String errorcode = rspContent.getString("error_no");
            String errormsg = rspContent.getString("error_info");
            throw new BusinessException(errormsg, errorcode);
        }
        JSONArray datalists = rspContent.getJSONArray("item");
        returnsResult = datalists.toJavaList(QueryCangDanFreezeDTO.class);
        return returnsResult;
    }

    //查询电子仓单转让指令
    public List<QueryCangDanTransferDTO> queryCangDanTransfer(QueryCangDanTransferReq requestObj) {
        List<QueryCangDanTransferDTO> returnsResult = new ArrayList<>();
        JSONObject json = new JSONObject();
        json.put("command_ids",requestObj.getCommand_ids());
        json.put("cargokey",requestObj.getCargokey());
        json.put("channel_no",requestObj.getChannel_no());
        // 1.请求参数json串reqContent
        String reqContent = json.toJSONString();
        // 2.随机生成的16位数字，用于签名（双方提前约定一串固定字符串，不在接口中传输）APP_ID: rzPort22
        String appSecret = mainBusinessConfig.getDzcdAppSecret();
        // 3.当前时间戳14位字符串timestamp，格式为"yyyyMMddHHmmss"
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 4.对reqContent+appSecret+timestamp拼接后的字符串通过SM3算法进行签名，得到64位摘要字符串sign
        String plain = reqContent + appSecret + timestamp;
        String charset = "UTF-8";
        String sign = SM3Factory.getInstance().hashAndReturnHex(plain, charset);

        Map<String, String> header = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("function_id", CangDanUriEnum.CARGO_TRANSFER_QUERY.getUrl());
        params.put("app_id", mainBusinessConfig.getDzcdAppId());
        params.put("timestamp", timestamp);
        params.put("sign", sign);
        params.put("req_content", json);
        JSONObject apiResult = newRzgApiHelper.sendApiLog(CangDanUriEnum.CARGO_TRANSFER_QUERY.getCode(),
                mainBusinessConfig.getDzcdUrl(), header, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, requestObj);
        String code = apiResult.getString("error_code");
        if (!SUCCESS_FLAG.equals(code)) {
            String errorcode = code;
            String errormsg = apiResult.getString("error_msg");
            throw new BusinessException(errormsg, errorcode);
        }
        JSONObject rspContent= apiResult.getJSONObject("rsp_content");
        if (!SUCCESS_FLAG.equals(rspContent.getString("error_no"))) {
            String errorcode = rspContent.getString("error_no");
            String errormsg = rspContent.getString("error_info");
            throw new BusinessException(errormsg, errorcode);
        }
        JSONArray datalists = rspContent.getJSONArray("item");
        returnsResult = datalists.toJavaList(QueryCangDanTransferDTO.class);
        return returnsResult;
    }
}
